package com.zky.utils;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@ConditionalOnClass(StringRedisTemplate.class)
@RequiredArgsConstructor
public class RedisUtil {

    private final StringRedisTemplate redisTemplate;


    // 存对象
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value));
    }

    // 存对象并设置过期时间
    public void set(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), timeout, unit);
    }

    // 取对象
    public <T> T get(String key, Class<T> clazz) {
        String json = redisTemplate.opsForValue().get(key);
        if (json == null) {
            return null;
        }
        return JSONUtil.toBean(json, clazz);
    }

    // 取集合
    public <T> List<T> getList(String key, Class<T> clazz) {
        String json = redisTemplate.opsForValue().get(key);
        if (json == null) {
            return null;
        }
        return JSONUtil.toList(json, clazz);
    }

    // 删除
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    //从set里取
    public <T> List<T> getListForSet(String key, Class<T> clazz) {

        Set<String> set = redisTemplate.opsForSet().members(key);
        List<T>list = new ArrayList<>();
        for (String s : set) {
            list.add(JSONUtil.toBean(s, clazz));
        }
        return list;
    }

    //往set里存
    public void addForSet(String key, Object value) {
        redisTemplate.opsForSet().add(key, JSONUtil.toJsonStr(value));
    }

    //从set里删除
    public void deleteForSet(String key, Object value) {
        redisTemplate.opsForSet().remove(key, value);
    }

}
